//
//  TT_GDMapManager.m
//  BaseProject
//
//  Created by 王洋 on 2020/4/8.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "TT_GDMapManager.h"
#import "TT_GDAnnotationView.h"

@interface TT_GDMapManager()<
MAMapViewDelegate,
AMapSearchDelegate,
AMapLocationManagerDelegate
>

@end

@implementation TT_GDMapManager

+ (TT_GDMapManager *)shareMap {
    
    static TT_GDMapManager *shareInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        shareInstance = [TT_GDMapManager new];
        [shareInstance initParam];
    });
    return shareInstance;
}

#pragma mark 初始化地图key
- (void)initMapSDK {
    //高德地图 设置APIKEY
    [AMapServices sharedServices].apiKey = @"13b4137af80dc913d998dfdad64f7305";
    [AMapServices sharedServices].enableHTTPS = YES;
    [AMapLocationManager updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    [AMapLocationManager updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
    [MAMapView updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
    [MAMapView updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    [[AMapNaviManagerConfig sharedConfig] updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
    [[AMapNaviManagerConfig sharedConfig] updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
}

#pragma mark 初始化，是否在移动地图位置的时候，拿到地址信息
- (void)initParam {
    self.isRegeocodeSearchOpen = NO;
}

#pragma mark -------布局地图-------
#pragma mark 获取定位信息
- (void)mapView_loadWithContainerView:(UIView *)containerView {
    
    [containerView addSubview:self.mapView];
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.mas_equalTo(0);
    }];
    
    WEAKSELF  //布局完后顺便获取下当前所在的位置点
    [self location_getCurrentLocationComption:^(CLLocation * _Nonnull location, BOOL success, NSError * _Nonnull error) {
        
        if (success) {
            weakSelf.mapView.centerCoordinate = location.coordinate;
            [weakSelf stopSerialLocation];//定位成功后结束定位
        } else {
            [TT_Alert alert:error.userInfo.description doneAction:^{}];
        }
    }];
}

#pragma mark 将地图中心移动到某一点
- (void)mapView_moveMapCenterToLocation:(CLLocationCoordinate2D)coordinate {
    self.mapView.centerCoordinate = coordinate;
}

#pragma mark 添加大头针
- (void)mapView_addPointWithPointAnnotation:(MAPointAnnotation *)pointAnnotation {
    [self.mapView addAnnotation:pointAnnotation];
}

#pragma mark 添加多个大头针
- (void)mapView_setManyPointWithArray:(NSMutableArray <MAMultiPointItem *>*)items {
     MAMultiPointOverlay *_overlay = [[MAMultiPointOverlay alloc] initWithMultiPointItems:items];
    [self.mapView addOverlay:_overlay];
}

#pragma mark -------定位相关-------
#pragma mark 获取当前定位位置
- (void)location_getCurrentLocationComption:(void (^)(CLLocation *location, BOOL success, NSError *error))comption {

    if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {

        [self startSerialLocation];
        WEAKSELF
        self.getLocationCallBackBlock = ^(CLLocation * _Nonnull location, BOOL success, NSError * _Nonnull error) {
            [weakSelf stopSerialLocation];//定位成功后结束定位
            comption(location, success, error);
        };

    } else {

        [TT_Alert alert:@"请打开定位权限" doneAction:^{}];
    }
}

#pragma mark 获取当前地图中心点位置
- (void)mapView_getMapCenterLocationComption:(void (^)(CLLocationCoordinate2D))comption {
    self.isRegeocodeSearchOpen = YES;
    self.getCenterLocationCallBackBlock = ^(CLLocationCoordinate2D coordinate) {
        comption(coordinate);
    };
}

#pragma mark 开始定位
- (void)startSerialLocation {
    [self.locationManager startUpdatingLocation];
}

#pragma mark 结束定位
- (void)stopSerialLocation {
    [self.locationManager stopUpdatingLocation];
}

#pragma mark 定位失败
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"%s, amapLocationManager = %@, error = %@", __func__, [manager class], error);
    if (self.getLocationCallBackBlock) {
        self.getLocationCallBackBlock([CLLocation new],NO,error);
    }
}

#pragma mark 获取某个点的地址 这个点可以是中心点也可以是别的点
- (void)regeo_getAddressWithCoordinate:(CLLocationCoordinate2D)coordinate comption:(void (^)(AMapReGeocodeSearchResponse *response))comption {
    self.getReGeocodeSearchResponseCallBackBlock = ^(AMapReGeocodeSearchResponse * _Nonnull response) {
        comption(response);
    };
}

#pragma mark 发起经纬度转地址，回调在代理中
- (void)regeo_requestReGeocodeSearchWithCoordinate:(CLLocationCoordinate2D)coordinate {
    _regeoCodeSearchRequest = [[AMapReGeocodeSearchRequest alloc] init];
    _regeoCodeSearchRequest.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    _regeoCodeSearchRequest.requireExtension = YES;
    [self.searchApi AMapReGoecodeSearch:_regeoCodeSearchRequest];
}

#pragma mark ----- MapView  Delegate -----
- (void)mapView:(MAMapView *)mapView mapWillMoveByUser:(BOOL)wasUserAction {
    NSLog(@"将要发生移动");
}

- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction {
    NSLog(@"移动完了");
}

#pragma mark 地图移动回调
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    NSLog(@"%f",mapView.region.center.latitude); //拿到中心点的经纬度
    NSLog(@"%f\n",mapView.region.center.longitude);

    //将获取到的中心点传出去
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = mapView.region.center.latitude;
    coordinate.longitude = mapView.region.center.longitude;
    
    if (self.getCenterLocationCallBackBlock) {
        self.getCenterLocationCallBackBlock(coordinate);
    }
    
    //由移动地图触发的经纬度解析地址   受isRegeocodeSearchOpen来控制
    if (self.isRegeocodeSearchOpen) {
        [self regeo_requestReGeocodeSearchWithCoordinate:coordinate];
    }
}

#pragma mark 气泡&&大头针
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    
    if ([annotation isKindOfClass:[MAUserLocation class]]) {
        return nil;;
    }
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        TT_GDAnnotationView *annotationView = (TT_GDAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[TT_GDAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:reuseIndetifier];
        }
        
        annotationView.image = [UIImage imageNamed:@"locationIcon"];
        annotationView.canShowCallout = NO;
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        //设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -15);
        return annotationView;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didAnnotationViewCalloutTapped:(MAAnnotationView *)view {
    NSLog(@"didAnnotationViewCalloutTapped点击了气泡");
}

- (void)mapView:(MAMapView *)mapView didAnnotationViewTapped:(MAAnnotationView *)view {
    NSLog(@"didAnnotationViewTapped点击了气泡");
}

#pragma mark ----- Location  Delegate -----
#pragma mark 定位结果
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location {
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    
    if (self.getLocationCallBackBlock) {
        self.getLocationCallBackBlock(location,YES,[NSError new]);
    }
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
    NSLog(@"reGeocode ------ location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    
    if (self.getLocationCallBackBlock) {
        self.getLocationCallBackBlock(location,YES,[NSError new]);
    }
}

#pragma mark ----- Search  Delegate -----
#pragma mark 获取地址信息的回调
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response {

    if (self.getReGeocodeSearchResponseCallBackBlock) {
        self.getReGeocodeSearchResponseCallBackBlock(response);
    }
}

#pragma mark ReGeocode出错的回调
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error {
}

- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response {
//    NSLog(@"reGeocode:%@", response.geocodes.firstObject.city);//获得的中心点地址
}

- (MAMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MAMapView alloc] init];
        ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
        _mapView.showsUserLocation = YES;
        _mapView.userTrackingMode = 1;
        _mapView.userTrackingMode = MAUserTrackingModeFollow;
        //设置地图缩放比例，即显示区域
        [_mapView setZoomLevel:15.1 animated:YES];
        _mapView.delegate = self;
        //设置定位精度
        _mapView.desiredAccuracy = kCLLocationAccuracyBest;
        //设置定位距离
        _mapView.distanceFilter = 5.0f;
    }
    return _mapView;;
}

- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc] init];
        _locationManager.delegate = self;
        [_locationManager setPausesLocationUpdatesAutomatically:NO];
    }
    return _locationManager;
}

- (AMapSearchAPI *)searchApi {
    if (!_searchApi) {
        _searchApi = [[AMapSearchAPI alloc] init];
        _searchApi.delegate = self;
    }
    return _searchApi;;
}


@end
